#ifndef _M_BD_H_
#define _M_BD_H_
#include "util.hpp"
#include <mutex>
#include <cassert>

class user_table
{
private:
    MYSQL *_mysql;     // mysql操作句柄
    std::mutex _mutex; // 互斥锁保护数据库的访问操作

public:
    user_table(const std::string &host, const std::string &username,
               const std::string &password, const std::string &dbname, uint16_t port = 3306)
    {
        _mysql = mysql_util::mysql_create(host, username, password, dbname, port);
        assert(_mysql != NULL);
    }
    ~user_table()
    {
        mysql_util::mysql_destroy(_mysql);
        _mysql = NULL;
    }

    // 注册时新增用户
    bool insert(Json::Value &user)
    {
#define INSERT_USER "insert user values(null,'%s',password('%s'),1000,0,0);"
        // sprintf(void* buf,char* format,...)
        if (user["password"].isNull() || user["username"].isNull())
        {
            DBG_LOG("INPUT PASSWORD OR USERNAME");
            return false;
        }
        char buf[4096] = {0};
        sprintf(buf, INSERT_USER, user["username"].asCString(), user["password"].asCString());
        bool ret = mysql_util::mysql_exec(_mysql, buf);
        if (ret == false)
        {
            DBG_LOG("INSERT USER INFO FAILED!");
            return false;
        }
        return true;
    }

    // 登录验证，并返回详细的用户信息
    bool login(Json::Value &user)
    {
        if (user["password"].isNull() || user["username"].isNull())
        {
            DBG_LOG("INPUT PASSWORD OR USERNAME!");
            return false;
        }
        // 以用户名和密码共同作为查询过滤条件，查询到数据则表示用户名密码一致，没有信息则用户名密码错误
#define LOGIN_USER "select id, score, total_count, win_count from user where username='%s' and password=password('%s');"
        char buf[4096] = {0};
        sprintf(buf, LOGIN_USER, user["username"].asCString(), user["password"].asCString());
        MYSQL_RES *res = NULL;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            bool ret = mysql_util::mysql_exec(_mysql, buf);
            if (ret == false)
            {
                DBG_LOG("USER LOGIN FAILED!");
                return false;
            }
            // 保存查询结果到本地
            res = mysql_store_result(_mysql);
            if (res == NULL)
            {
                DBG_LOG("HAVE NO LOGIN USER INFO!");
                return false;
            }
        }
        // 要么没有数据，要么只有一条数据
        int row_num = mysql_num_rows(res);
        if (row_num != 1)
        {
            DBG_LOG("THE USER INFORMATION QUERIED IS NOT UNIQUE!");
            return false;
        }
        // 遍历结果集，并且这个接口会保存当前读取位置，每次获取的都是下一条数据
        MYSQL_ROW row = mysql_fetch_row(res);
        user["id"] = (Json::UInt64)std::stol(row[0]);
        user["score"] = (Json::UInt64)std::stol(row[1]);
        user["total_count"] = std::stoi(row[2]);
        user["win_count"] = std::stoi(row[3]);
        // 释放结果集
        mysql_free_result(res);
        return true;
    }

    // 通过用户名获取用户信息
    bool select_by_name(const std::string &name, Json::Value &user)
    {
#define USER_BY_NAME "select id, score, total_count, win_count from user where username='%s';"
        char buf[4096] = {0};
        sprintf(buf, USER_BY_NAME, name.c_str());
        MYSQL_RES *res = NULL;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            bool ret = mysql_util::mysql_exec(_mysql, buf);
            if (ret == false)
            {
                DBG_LOG("GET USER BY NAME FAILED!");
                return false;
            }
            // 要么没有数据，要么只有一条数据
            res = mysql_store_result(_mysql);
            if (res == NULL)
            {
                DBG_LOG("HAVE NO USER INFO!");
                return false;
            }
        }
        int row_num = mysql_num_rows(res);
        if (row_num != 1)
        {
            DBG_LOG("THE USER INFORMATION QUERIED IS NOT UNIQUE!");
            return false;
        }
        MYSQL_ROW row = mysql_fetch_row(res);
        user["id"] = (Json::UInt64)std::stol(row[0]);
        user["username"] = name;
        user["score"] = (Json::UInt64)std::stol(row[1]);
        user["total_count"] = std::stoi(row[2]);
        user["win_count"] = std::stoi(row[3]);
        mysql_free_result(res);
        return true;
    }

    // 通过用户id获取用户信息
    bool select_by_id(uint64_t id, Json::Value &user)
    {
#define USER_BY_ID "select username, score, total_count, win_count from user where id=%d;"
        char buf[4096] = {0};
        sprintf(buf, USER_BY_ID, id);
        MYSQL_RES *res = NULL;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            bool ret = mysql_util::mysql_exec(_mysql, buf);
            if (ret == false)
            {
                DBG_LOG("GET USER BY ID FAILED!");
                return false;
            }
            // 要么没有数据，要么只有一条数据
            res = mysql_store_result(_mysql);
            if (res == NULL)
            {
                DBG_LOG("HAVE NO USER INFO!");
                return false;
            }
        }
        int row_num = mysql_num_rows(res);
        if (row_num != 1)
        {
            DBG_LOG("THE USER INFORMATION QUERIED IS NOT UNIQUE!");
            return false;
        }
        MYSQL_ROW row = mysql_fetch_row(res);
        user["id"] = (Json::UInt64)id;
        user["username"] = row[0];
        user["score"] = (Json::UInt64)std::stol(row[1]);
        user["total_count"] = std::stoi(row[2]);
        user["win_count"] = std::stoi(row[3]);
        mysql_free_result(res);
        return true;
    }

    // 胜利时，天梯分数+30，战斗场次增加1，胜利场次增加1
    bool win(uint64_t id)
    {
#define USER_WIN "update user set score=score+30, total_count=total_count+1, win_count=win_count+1 where id=%d;"
        char buf[4096] = {0};
        sprintf(buf, USER_WIN, id);
        bool ret = mysql_util::mysql_exec(_mysql, buf);
        if (ret == false)
        {
            DBG_LOG("UPDATA WIN USER INFO FAILED!");
            return false;
        }
        return true;
    }

    // 失败时，天梯分数-30，战斗场次增加1
    bool lose(uint64_t id)
    {
#define USER_LOSE "update user set score=score-30, total_count=total_count+1 where id=%d;"
        char buf[4096] = {0};
        sprintf(buf, USER_LOSE, id);
        bool ret = mysql_util::mysql_exec(_mysql, buf);
        if (ret == false)
        {
            DBG_LOG("UPDATA LOSE USER INFO FAILED!");
            return false;
        }
        return true;
    }
};

#endif /* _M_BD_H_ */
